// https://leetcode.cn/problems/minimize-the-maximum-difference-of-pairs/

class Solution {
public:
    int minimizeMax(vector<int>& a, int p) {
        sort(a.begin(), a.end());
        int l = -1, r = a.back() - a[0] + 1;
        
        auto check = [&](int mid) -> bool {
            int cnt = 0;
            for (int i = 0; i < a.size() - 1; i++) {
                if (a[i + 1] - a[i] <= mid) {
                    cnt++; i++;
                }
            }
            return cnt >= p;
        };
        
        while (l + 1 < r) {
            int mid = l + r >> 1;
            if (check(mid)) r = mid;
            else l = mid;  
        }
        return r;
    }
};